import { reqGetCode, reqUserAddressList, reqUserLogin, reqUserLogout, reqUserRegister,reqGetUserInfo} from '@/network';
import {getUserTempId} from '@/utils/userabout';


const state = {
 userTempId: getUserTempId(),
 code: '',
 token: localStorage.getItem('TOKEN_KEY'),
 userInfo: {},
 userAddressList: []
}

const actions = {
    async userRegister({commit},userInfo) {
        const result = await reqUserRegister(userInfo);
        if(result.code === 200) {
            return 'ok'
        }else {
            return Promise.reject(new Error('failed'))
        }
    },
    async getCode({commit},phone) {
        const result = await reqGetCode(phone);
        if(result.code === 200) {
            commit('RECEIVE_CODE',result.data);
            return 'ok'
        }else {
            return Promise.reject(new Error('failed'))
        }
    },
     async userLogin({commit},userInfo) {
        const result = await reqUserLogin(userInfo);
        if(result.code === 200) {
            commit('RECEIVE_TOKEN',result.data.token);
            localStorage.setItem('TOKEN_KEY',result.data.token)
            return 'ok'
        }else {
            return Promise.reject(new Error('failed'))
        }
    },
    async getUserInfo({commit}) {
        const result = await reqGetUserInfo();
        console.log('getUserInfo',result);
        if(result.code === 200) {
            commit('RECEIVE_USERINFO',result.data);
            return 'ok'
        }else {
            return Promise.reject(new Error('failed'))
        }
    },
    async clearToken({commit}) {
        commit('RESET_TOKEN');
        localStorage.removeItem('TOKEN_KEY')
    },
    async userLogout({commit}) {
        const result = await reqUserLogout();
        if(result.code === 200) {
            commit('RESET_USER');
            localStorage.removeItem('TOKEN_KEY')
            return 'ok'
        }else {
            return Promise.reject(new Error('failed'))
        }
    },
    async getUserAddressList({commit}) {
        const result = await reqUserAddressList();
        if(result.code === 200) {
            commit('RECEIVE_USERADDRESSLIST',result.data);
        }
    },
}

const mutations = {
   RECEIVE_CODE(state,code) {
        state.code = code
   },
   RECEIVE_TOKEN(state,token) {
        state.token = token
   },
   RECEIVE_USERINFO(state,userInfo) {
        state.userInfo = userInfo
   },
   RESET_TOKEN(state) {
        state.token = ''
   },
   //清空用户信息
   RESET_USER(state) {
       state.token = ''
       state.userInfo = {}
   },
   RECEIVE_USERADDRESSLIST(state,userAddressList) {
       state.userAddressList = userAddressList
   }
}

const getters = {
    
}

export default {
    state,
    actions,
    mutations,
    getters
}